# -*- coding:utf-8 -*-
# @Project:
# @File:
# @Date:
# @Author:Joe
# @Description:
from selenium.common.exceptions import ElementClickInterceptedException, TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
import allure
from common.log import log
from config.conf import ALLURE_IMG_DIR
from time import sleep
import re


class BasicOperation:
    def __init__(self, driver):
        self.driver = driver

    # @allure.step("打开网站")
    def get_url(self, url):
        try:
            self.driver.get(url)
            log.info(f'打开网站：{url}')
            return self.driver
        except Exception as e:
            raise e

    # @allure.step("退出浏览器")
    def quit(self):
        try:
            self.driver.quit()
            log.info("退出浏览器")
        except Exception as e:
            raise e

    # @allure.step("输入框输入值")
    def input_box(self, ele, value, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(ele))
            element.clear()
            element.send_keys(value)
            log.info(f'输入框输入值：{value}')
            return True
        except Exception as e:
            log.error(f"输入框错误，{e}")
            raise e

    # @allure.step("点击元素")
    def sel_click(self, ele, timeout=20):
        try:
            WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(ele)).click()
            sleep(0.2)
            selen = re.sub('[^\u4e00-\u9fa5]+', '', str(ele))
            if len(selen) > 0:
                log.info(f'点击元素：{selen}')
            else:
                log.info(f'点击元素element：{ele}')
        except ElementClickInterceptedException as ecie:
            print("执行了ElementClickInterceptedException")
            log.error(f"点击元素错误，获取href链接，错误信息：{ecie}")
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(ele))
            click_url = element.get_attribute('href')
            log.info(f"获取href链接：{click_url}")
            try:
                if_blank = element.get_attribute('target')
                if if_blank == '_blank':
                    # 打开新窗口，并记录其URL
                    self.driver.execute_script(f"window.open('{click_url}', '_blank');")
                    log.info(f"新窗口打开：{click_url}")
                    sleep(0.5)
                    # # 获取所有窗口句柄
                    # all_window_handles = self.driver.window_handles
                    # # 切换到新窗口
                    # self.driver.switch_to.window(all_window_handles[-1])
                else:
                    self.driver.get(click_url)
                    log.info(f"当前窗口打开：{click_url}")
            except:
                self.driver.get(click_url)
                log.info(f"当前窗口打开：{click_url}")
        except Exception as e:
            print("执行了exception")
            log.error(f"无法定位到元素：{ele}，异常为: \n{e}")
            raise e

    @allure.step("获取指定元素的text值")
    def get_text(self, els, timeout=10, mode=0):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(els))
            if mode == 0:
                text = element.text
                log.info(f"获取text:{text}")
                return text
            elif mode == 1:
                text = element.get_attribute('textContent')
                log.info(f"获取textContent:{text}")
                return text
        except Exception as e:
            print(f"get_text错误，{e}")
            return None

    @allure.step("获取元素的href")
    def get_href(self, ele, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(ele))
            ele_href = element.get_attribute('href')
            log.info(f"获取元素的href：{ele_href}")
            return ele_href
        except Exception as e:
            log.error(f"获取href错误，{e}")
            raise e

    @allure.step("返回上一页")
    def back_page(self):
        self.driver.back()
        log.info('返回上一页')
        try:
            WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
            log.info("页面已返回并加载完成")
        except TimeoutException as et:
            log.error("页面返回超时或未加载完成")
            raise et
        except Exception as e:
            log.error(f"返回上一页发生异常: {e}")
            raise e

    @allure.step("切换到新标签页")
    def switch_to_window(self):
        try:
            windows = self.driver.window_handles
            self.driver.switch_to.window(windows[-1])
            log.info(f'切换到新标签页：{windows[-1]}')
        except Exception as e:
            log.error(f"切换到新标签页发生异常: {e}")
            raise e

    @allure.step("关闭当前标签页")
    def close_window(self):
        try:
            self.driver.close()
            log.info('关闭标签页')
        except Exception as e:
            log.error(f"关闭标签页发生异常: {e}")
            raise e

    @allure.step("判断复选框是否被选中，选择复选框")
    def is_selected(self, ele, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(ele))
            if element.is_selected():
                log.info('复选框已选中')
                return True
            else:
                element.click()
                log.info('复选框未选中，已选择')
                return True
        except Exception as e:
            log.error(f"选择复选框错误，{e}")
            raise e

    @allure.step("获取指定元素的text列表")
    def get_text_list(self, els, timeout=20, mode=0):
        try:
            elements = WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(els))
            text_list = []
            for element in elements:
                if mode == 0:
                    text_list.append(element.text.strip())
                elif mode == 1:
                    # log.info(element.get_attribute('textContent'))
                    text_list.append(element.get_attribute('textContent').strip())
            log.info(f"获取text列表：{text_list}")
            return text_list
        except Exception as e:
            print(f"获取文本列表错误，{e}")
            return None

    @allure.step("获取element元素")
    def get_element(self, ele, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(ele))
            return element
        except Exception as e:
            print(f"获取element元素错误，{e}")
            return None

    @allure.step("获取page_source")
    def get_page_source(self):
        try:
            page_source = self.driver.page_source
            return page_source
        except Exception as e:
            print(f"获取page_source错误，{e}")
            return None

    @allure.step("切换到iframe")
    def switch_to_frame(self, ele):
        try:
            self.driver.switch_to.frame(ele)
            log.info('切换到iframe')
            return True
        except Exception as e:
            log.error(f"切换到iframe错误，{e}")
            raise e

    @allure.step("切换到默认frame")
    def switch_to_default_content(self):
        try:
            self.driver.switch_to.default_content()
            log.info('切换到默认frame')
            return True
        except Exception as e:
            log.error(f"切换到默认frame错误，{e}")
            raise e

    @allure.step("获取指定元素的value值")
    def get_value(self, ele, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(ele))
            ele_value = element.get_attribute('value')
            log.info(f"获取元素value值为：{ele_value}")
            return ele_value
        except Exception as e:
            print(f"获取元素value值错误，{e}")
            raise e

    @allure.step("select下拉选择")
    def select_box(self, ele, value, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(
                EC.element_to_be_clickable(ele)
            )
            select = Select(element)
            select.select_by_value(value)
            log.info(f'select下拉选择：{value}')
            return True
        except Exception as e:
            log.error(f"select下拉选择错误，{e}")
            raise e

    @allure.step("点击按钮")
    def click_button(self, ele, timeout=20):
        try:
            elements = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(ele))
            sleep(0.2)
            selen = re.sub('[^\u4e00-\u9fa5]+', '', str(ele))
            if len(selen) > 0:
                log.info(f'点击元素：{selen}')
            else:
                log.info(f'点击元素element：{ele}')
        except Exception as e:
            log.error(f"无法定位到元素：{ele}，异常为: \n{e}")
            raise e

    @allure.step("获取target内容")
    def get_target(self, ele, timeout=10):
        try:
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(ele))
            if_blank = element.get_attribute('target')
            log.info(f"获取target内容，{if_blank}")
            return if_blank
        except Exception as e:
            log.error(f"获取target错误，{e}")
            raise e

    @allure.step("获取元素列表的href列表")
    def get_href_list(self, els, timeout=30):
        try:
            elements = WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(els))
            href_list = []
            for element in elements:
                href_list.append(element.get_attribute('href'))
            log.info(f"获取元素的href列表：{href_list}")
            return href_list
        except Exception as e:
            log.error(f"获取href列表错误，{e}")
            raise e

    @allure.step("打开新空白标签页")
    def open_new_tab(self, url):
        try:
            self.driver.execute_script(f"window.open('{url}')")
            log.info(f"打开新标签页：{url}")
            return True
        except Exception as e:
            log.error(f"打开新标签页错误，{e}")
            raise e

    @allure.step("判断列表是否无数据")
    def is_element_exist(self, ele):
        try:
            element = WebDriverWait(self.driver, 1).until(EC.presence_of_element_located(ele))
            text = element.text
            print(text)
            if "无数据" in text:
                return False
            else:
                return True
        except:
            if "无数据" in ele[1]:
                return True
            else:
                return False

    @allure.step("判断下拉框是否可见")
    def is_select_visible(self, ele):
        try:
            element = WebDriverWait(self.driver, 1).until(EC.presence_of_element_located(ele))
            if element.is_displayed():
                return True
            else:
                return False
        except:
            return False
